package com.cmes.system.web.controller;

import com.cmes.core.Pagination;
import com.cmes.core.annotation.OperateLog;
import com.cmes.core.domain.bo.IdsBO;
import com.cmes.core.utils.BeanUtils;
import com.cmes.core.utils.CollectionUtils;
import com.cmes.jdbc.customquery.CustomQueryBO;
import com.cmes.system.api.bo.UserBO;
import com.cmes.system.core.entity.UserEntity;
import com.cmes.system.core.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 用户管理
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class UserController {

    private final String MODULE = "用户管理";
    private final UserService userService;

    @PostMapping("search")
    public Pagination<UserEntity> search(@RequestBody @Valid CustomQueryBO bo) {
        return userService.page(bo);
    }

    @OperateLog(module = MODULE, businessType = "ADD")
    @PostMapping("add")
    public Long add(@RequestBody @Valid UserBO.AddBO bo) {
        UserEntity entity = BeanUtils.copyProperties(bo, new UserEntity());
        userService.canAdd(entity);
        userService.addUser(entity, CollectionUtils.singletonList(bo.getDeptId()), bo.getRoleIds());
        return entity.getId();
    }

    @OperateLog(module = MODULE, businessType = "UPDATE")
    @PostMapping("update")
    public Long update(@RequestBody @Valid UserBO.UpdateBO bo) {
        UserEntity entity = BeanUtils.copyProperties(bo, new UserEntity());
        userService.canUpdate(entity);
        userService.updateUser(entity, CollectionUtils.singletonList(bo.getDeptId()), bo.getRoleIds());
        return entity.getId();
    }

    @OperateLog(module = MODULE, businessType = "DELETE")
    @PostMapping("delete")
    public void delete(@RequestBody @Valid IdsBO bo) {
        userService.canDelete(bo.getIds());
        userService.deleteUser(bo.getIds());
    }

    @OperateLog(module = MODULE, businessType = "DISABLE")
    @PostMapping("disable")
    public void disable(@RequestBody @Valid IdsBO bo) {
        userService.canDisable(bo.getIds());
        userService.disable(bo.getIds());
    }

    @OperateLog(module = MODULE, businessType = "ENABLE")
    @PostMapping("enable")
    public void enable(@RequestBody @Valid IdsBO bo) {
        userService.canEnable(bo.getIds());
        userService.enable(bo.getIds());
    }

}
